package ynu.edu.utils.Interceptor;

import com.auth0.jwt.JWT;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import ynu.edu.common.exception.ServiceException;
import ynu.edu.utils.inna.AuthPermission;
import ynu.edu.dao.IUserDao;
import ynu.edu.entity.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserDao userDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();

        AuthPermission annotation = method.getAnnotation(AuthPermission.class);
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }


        if (annotation != null) {
            // 获取注解中定义的角色要求
            String requiredRole = annotation.role();
            //能通过第一个拦截器说明已经登录，直接获取用户数据
            String userPhone = JWT.decode(token).getAudience().get(0);
            System.out.println("requiredRole = " + requiredRole);

            // 根据 token 的 userPhone 查询
            User user = userDao.findUserByUserPhone(userPhone);

            if (user == null || !requiredRole.equals(user.getType())) {
                throw new ServiceException("403", "权限不足，无法访问");
            }
            return true;
        }
        return true;
    }
}
